# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  helper :all # include all helpers, all the time
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  before_filter :login_in_2_thread,:authorize,:error_message_follows_field

  # Scrub sensitive parameters from your log
  filter_parameter_logging :password
   
  # 校验错误信息显示在field后面
  def error_message_follows_field
    ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
      if instance.error_message.kind_of?(Array)
        %(#{html_tag}<span class="validation_error">&nbsp;  #{instance.error_message.join(',')}</span>)
      else
        %(#{html_tag}<span class="validation_error">&nbsp;  #{instance.error_message}</span>)
      end
    end
  end

  def login_in_2_thread
    # TODO: 国际化，默认中文，暂时没搞定配置
    I18n.locale = :'zh-CN'
    Thread.current[:current_user_id] = session[:current_user_id]
  end

  # 登录超时验证
  def authorize
    if session[:current_user_id].nil?
      session[:the_last_request_uri] = request.request_uri
      redirect_to new_session_url()
    end
  end
  
  # 发送短信并render
  def send_sm_and_render_when_failed
    begin
      yield
    rescue Exception => error
      logger.error "======================="
      logger.error error
      logger.error "======================="      
      render :status => 500 , :text => error
    end
#  rfetion v>=0.5.7
#    rescue Fetion::PasswordMaxError => error
#      logger.error error
#      render :status => 500 , :text => '错误尝试次数过多，请用飞信客户端登录取消该限制，请稍候重试。'
#    rescue Fetion::PasswordError => error
#      logger.error error
#      render :status => 500 , :text => '密码不正确,再试试。'
#    rescue Fetion::SipcException => error
#      logger.error error
#      render :status => 500 , :text => '飞信发送组件失效,请联系管理员解决。'
#    rescue SocketError
#      logger.error error
#      render :status => 500 , :text => '飞信服务器断网,请联系管理员解决。'
#    end
  end
end
